﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using System.Management;
using System.Net; 

namespace MDK
{
    class MDK2Keil
    {
        public enum OutVSProjectPath
        {
            SameAsMDK,
            NewSameNameFolder,
            NewSpecificFolder
        }
        string VSProjectNewSubFolder;         //生成的VS的工程的子文件夹，如果为空则与keil工程同文件夹
        public string IncludePath;            //Keil工程的IncludePath
        public string KeilProjFullName;       //Keil工程的完整路径
        private string ProjName;              //工程名称
        private string KeilProjPath;          //Keil工程的路径，不包括keil工程文件名
        public string VSProjPath;            //VS工程的的路径，不包括vs工程文件名
        private string UV4_Path;              //MDK的安装路径
        private string LocalDebuggerCommandArguments;
        private XmlDocument xmlDoc = new XmlDocument();   //用于解析MDK工程文件

        private string LocalDebuggerWorkingDirectory;
        private string NMakeBuildCommandLine;

        public bool CreateSln = false;
        public bool CreateVcproj = false;
        public bool CreateUserfile = false;
        public bool CreateReadme = false;


        public MDK2Keil(string docPath, string uv4Path)
        {
            KeilProjFullName = docPath;
            KeilProjPath = Path.GetDirectoryName(docPath) + "\\";

            ProjName = Path.GetFileNameWithoutExtension(docPath);
            UV4_Path = uv4Path;
            LocalDebuggerCommandArguments = "-d " + ProjName + ".uvproj -t \"Target\"";
            //LocalDebuggerWorkingDirectory = GetRelativePath(VSProjPath, KeilProjPath);
            NMakeBuildCommandLine = string.Concat(new string[]
			{
				"\"",
				UV4_Path,
				"\" -b ",
				LocalDebuggerWorkingDirectory,
				" -t \"Target\" -j0 -o Build.log"
			});
        }


        /// <summary>
        /// 获取 TargetName
        /// </summary>
        /// <returns></returns>
        public string[] MDK_TargetRead()
        {
            if (KeilProjFullName == "")
            {
                return null;
            }
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/*");
            string[] array = new string[xmlNodeList.Count];
            int num = 0;
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                array[num] = xmlNode.SelectSingleNode("./TargetName").InnerText;
                num++;
            }
            return array;
        }
        /// <summary>
        /// 获取 Device、Error、ListingPath、OutputDirectory、Define、IncludePath
        /// </summary>
        /// <param name="TargetName"></param>
        /// <returns></returns>
        public string[] MDK_TargetStatusRead(string TargetName)
        {
            if (KeilProjFullName == "")
            {
                return null;
            }
            if (TargetName == "")
            {
                return null;
            }
            string[] strStatuItem = new string[10];
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/Target");
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.SelectSingleNode("./TargetName").InnerText == TargetName)
                {
                    string str = "";
                    int item = 0;
                    //str = str + "Device: " + xmlNode.SelectSingleNode(".//Device").InnerText + "\r\n";
                    //str = str + "Error: " + xmlNode.SelectSingleNode(".//TargetStatus/Error").InnerText + "\r\n";
                    //str = str + "ListingPath: " + xmlNode.SelectSingleNode(".//TargetCommonOption/ListingPath").InnerText + "\r\n";
                    //str = str + "OutputDirectory: " + xmlNode.SelectSingleNode(".//TargetCommonOption/OutputDirectory").InnerText + "\r\n";
                    //str = str + "Define: " + xmlNode.SelectSingleNode(".//VariousControls/Define").InnerText + "\r\n";
                    //str += "IncludePath: \r\n";
                    //string text = xmlNode.SelectSingleNode(".//VariousControls/IncludePath").InnerText;
                    //text = text.Replace("..\\", "**\\");
                    //text = text.Replace(".\\", "..\\");
                    //text = text.Replace("**\\", "..\\");
                    //text = text.Replace(";", ";\r\n");
                    //return str + text;

                    strStatuItem[item++] = "Device:           " + xmlNode.SelectSingleNode(".//Device").InnerText;
                    strStatuItem[item++] = "Error:            " + xmlNode.SelectSingleNode(".//TargetStatus/Error").InnerText;
                    strStatuItem[item++] = "ListingPath:      " + xmlNode.SelectSingleNode(".//TargetCommonOption/ListingPath").InnerText;
                    strStatuItem[item++] = "OutputDirectory:  " + xmlNode.SelectSingleNode(".//TargetCommonOption/OutputDirectory").InnerText;
                    strStatuItem[item++] = "OutputName:       " + xmlNode.SelectSingleNode(".//TargetCommonOption/OutputName").InnerText;
                    strStatuItem[item++] = "ListingPath:      " + xmlNode.SelectSingleNode(".//TargetCommonOption/ListingPath").InnerText;
                    strStatuItem[item++] = "Define:           " + xmlNode.SelectSingleNode(".//VariousControls/Define").InnerText;
                    return strStatuItem;
                }
            }
            return null;
        }

        /// <summary>
        /// 获取预配置中的Define
        /// </summary>
        /// <param name="TargetName"></param>
        /// <returns></returns>
        public string MDK_DefineRead(string TargetName)
        {
            if (KeilProjFullName == "")
            {
                return "";
            }
            if (TargetName == "")
            {
                return "";
            }
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/Target");
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.SelectSingleNode("./TargetName").InnerText == TargetName)
                {
                    return xmlNode.SelectSingleNode(".//VariousControls/Define").InnerText;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取IncludePath
        /// </summary>
        /// <param name="TargetName"></param>
        /// <returns></returns>
        public string MDK_IncludePathRead(string TargetName)
        {
            if (KeilProjFullName == "")
            {
                return "";
            }
            if (TargetName == "")
            {
                return "";
            }
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/Target");
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.SelectSingleNode("./TargetName").InnerText == TargetName)
                {
                    return xmlNode.SelectSingleNode(".//VariousControls/IncludePath").InnerText;
                }
            }
            return null;
        }
        /// <summary>
        /// 获取GroupName
        /// </summary>
        /// <param name="TargetName"></param>
        /// <returns></returns>
        public string[] MDK_GroupRead(string TargetName)
        {
            if (KeilProjFullName == "")
            {
                return null;
            }
            if (TargetName == "")
            {
                return null;
            }
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/Target");
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.SelectSingleNode("./TargetName").InnerText == TargetName)
                {
                    XmlNodeList xmlNodeList2 = xmlNode.SelectNodes(".//Groups/*");
                    string[] array = new string[xmlNodeList2.Count];
                    int num = 0;
                    foreach (XmlNode xmlNode2 in xmlNodeList2)
                    {
                        array[num] = xmlNode2.SelectSingleNode("./GroupName").InnerText;
                        num++;
                    }
                    return array;
                }
            }
            return null;
        }

        public bool MDK_CheckProject()
        {
            if (KeilProjFullName == "")
            {
                return false;
            }
            bool result;
            try
            {
                xmlDoc.Load(KeilProjFullName);
                XmlNode xmlNode = xmlDoc.SelectSingleNode(".//Header");
                if (xmlNode == null)
                {
                    result = false;
                }
                else if (xmlNode.InnerText == "### uVision Project, (C) Keil Software")
                {
                    result = true;
                }
                else
                {
                    result = false;
                }
            }
            catch
            {
                result = false;
            }
            return result;
        }

        /// <summary>
        /// 读取src路径
        /// </summary>
        /// <param name="TargetName"></param>
        /// <param name="Group"></param>
        /// <returns></returns>
        public string[] MDK_SrcRead(string TargetName, string Group)
        {
            if (KeilProjFullName == "")
            {
                return null;
            }
            if (Group == "")
            {
                return null;
            }
            xmlDoc.Load(KeilProjFullName);
            XmlNodeList xmlNodeList = xmlDoc.SelectNodes(".//Targets/Target");
            foreach (XmlNode xmlNode in xmlNodeList)
            {
                if (xmlNode.SelectSingleNode("./TargetName").InnerText == TargetName)
                {
                    XmlNodeList xmlNodeList2 = xmlNode.SelectNodes(".//Groups/Group");
                    foreach (XmlNode xmlNode2 in xmlNodeList2)
                    {
                        if (xmlNode2.SelectSingleNode("./GroupName").InnerText == Group)
                        {
                            XmlNodeList xmlNodeList3 = xmlNode2.SelectNodes("./Files/File");
                            string[] array = new string[xmlNodeList3.Count];
                            int num = 0;
                            foreach (XmlNode xmlNode3 in xmlNodeList3)
                            {
                                string innerText = xmlNode3.SelectSingleNode("./FilePath").InnerText;
                                array[num] = innerText;
                                num++;
                            }
                            return array;
                        }
                    }
                }
            }
            return null;
        }


        public void VC_Creat_Sln(string[] Targets)
        {
            string DocName = VSProjPath + ProjName + ".sln";

            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("Microsoft Visual Studio Solution File, Format Version 11.00\r\n");
            stringBuilder.Append("# Visual Studio 2010\r\n");
            stringBuilder.Append("Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"Template\", \"Template.vcxproj\", \"{630C639D-C434-4F17-AB2D-5D46AF7B2116}\"");
            stringBuilder.Append("\r\nEndProject\r\n");
            stringBuilder.Append("Global\r\n");
            stringBuilder.Append("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution\r\n");
            for (int i = 0; i < Targets.Length; i++)
            {
                string newValue = Targets[i];
                string text = "\t\tDebug|Win32 = Debug|Win32\r\n";
                text = text.Replace("Debug", newValue);
                stringBuilder.Append(text);
            }
            stringBuilder.Append("\tEndGlobalSection\r\n");
            stringBuilder.Append("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution\r\n");
            string newValue2 = Guid.NewGuid().ToString("B");
            for (int j = 0; j < Targets.Length; j++)
            {
                string newValue3 = Targets[j];
                string text2 = "\t\tGUID.Debug|Win32.ActiveCfg = Debug|Win32\r\n";
                string text3 = "\t\tGUID.Debug|Win32.Build.0 = Debug|Win32\r\n";
                text2 = text2.Replace("GUID", newValue2);
                text2 = text2.Replace("Debug", newValue3);
                text3 = text3.Replace("GUID", newValue2);
                text3 = text3.Replace("Debug", newValue3);
                stringBuilder.Append(text2);
                stringBuilder.Append(text3);
            }
            stringBuilder.Append("\tEndGlobalSection\r\n");
            stringBuilder.Append("\t\tGlobalSection(SolutionProperties) = preSolution\r\n");
            stringBuilder.Append("\t\tHideSolutionNode = FALSE\r\n");
            stringBuilder.Append("\tEndGlobalSection\r\n");
            stringBuilder.Append("EndGlobal\r\n");
            stringBuilder = stringBuilder.Replace("Template", ProjName);
            FileStream fileStream = File.OpenWrite(DocName);
            byte[] bytes = new UTF8Encoding(true).GetBytes(stringBuilder.ToString());
            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Close();
            stringBuilder.Clear();
        }


        public void VC_vcxproj_Create(string[] Targets)
        {
            string DocName = VSProjPath + ProjName + ".vcxproj";
            if (DocName == "")
            {
                return;
            }
            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            XElement xElement = new XElement(ns + "Project", new object[]
			{
				new XAttribute("DefaultTargets", "Build"),
				new XAttribute("ToolsVersion", "4.0")
			});
            XElement xElement2 = new XElement(ns + "ItemGroup", new XAttribute("Label", "ProjectConfigurations"));
            for (int i = 0; i < Targets.Length; i++)
            {
                string text = Targets[i];
                xElement2.Add(new XElement(ns + "ProjectConfiguration", new object[]
				{
					new XAttribute("Include", "Target|Win32".Replace("Target", text)),
					new XElement(ns + "Configuration", text),
					new XElement(ns + "Platform", "Win32")
				}));
            }
            xElement.Add(xElement2);
            XElement content = new XElement(ns + "PropertyGroup", new object[]
			{
				new XAttribute("Label", "Globals"),
				new XElement(ns + "ProjectGuid", Guid.NewGuid().ToString("B")),
				new XElement(ns + "Keyword", "MakeFileProj")
			});
            xElement.Add(content);
            xElement.Add(new XElement(ns + "Import", new XAttribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props")));
            for (int j = 0; j < Targets.Length; j++)
            {
                string newValue = Targets[j];
                xElement.Add(new XElement(ns + "PropertyGroup", new object[]
				{
					new XAttribute("Condition", "'$(Configuration)|$(Platform)'=='Target|Win32'".Replace("Target", newValue)),
					new XAttribute("Label", "Configuration"),
					new XElement(ns + "ConfigurationType", "Makefile"),
					new XElement(ns + "UseDebugLibraries", "true")
				}));
            }
            xElement.Add(new object[]
			{
				new XElement(ns + "Import", new XAttribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props")),
				new XElement(ns + "ImportGroup", new XAttribute("Label", "ExtensionSettings"))
			});
            for (int k = 0; k < Targets.Length; k++)
            {
                string newValue2 = Targets[k];
                xElement.Add(new XElement(ns + "ImportGroup", new object[]
				{
					new XAttribute("Condition", "'$(Configuration)|$(Platform)'=='Target|Win32'".Replace("Target", newValue2)),
					new XAttribute("Label", "PropertySheets"),
					new XElement(ns + "Import", new object[]
					{
						new XAttribute("Project", "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props"),
						new XAttribute("Condition", "exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')"),
						new XAttribute("Label", "LocalAppDataPlatform")
					})
				}));
            }
            xElement.Add(new XElement(ns + "PropertyGroup", new XAttribute("Label", "UserMacros")));
            for (int l = 0; l < Targets.Length; l++)
            {
                string text2 = Targets[l];
                string text3 = IncludePath;
                string[] array = text3.Split(new char[]
				{
					';'
				});
                string text4 = null;
                for (int m = 0; m < array.Length; m++)
                {
                    string fullPath = GetFullPath(KeilProjPath, array[m]);
                    text4 = text4 + GetRelativePath(KeilProjPath, fullPath) + ";";
                }
                xElement.Add(new XElement(ns + "PropertyGroup", new object[]
				{
					new XAttribute("Condition", "'$(Configuration)|$(Platform)'=='Target|Win32'".Replace("Target", text2)),
					new XElement(ns + "NMakeOutput", "Template.exe".Replace("Template", ProjName)),
					new XElement(ns + "NMakePreprocessorDefinitions", MDK_DefineRead(text2)),
					new XElement(ns + "IncludePath", text4),
					new XElement(ns + "NMakeBuildCommandLine", NMakeBuildCommandLine.Replace("Target", text2))
				}));
            }
            xElement.Add(new XElement(ns + "ItemDefinitionGroup", ""));
            string[] array2 = MDK_GroupRead(Targets[0]);
            XElement xElement3 = new XElement(ns + "ItemGroup", "");
            XElement xElement4 = new XElement(ns + "ItemGroup", "");
            string[] array3 = array2;
            for (int n = 0; n < array3.Length; n++)
            {
                string group = array3[n];
                string[] array4 = MDK_SrcRead(Targets[0], group);
                string[] array5 = array4;
                for (int num = 0; num < array5.Length; num++)
                {
                    string targetPat = array5[num];
                    string text5 = GetFullPath(KeilProjPath, targetPat);
                    text5 = GetRelativePath(VSProjPath, text5);
                    if (text5.EndsWith(".c"))
                    {
                        xElement4.Add(new XElement(ns + "ClCompile", new XAttribute("Include", text5)));
                    }
                    else
                    {
                        xElement3.Add(new XElement(ns + "None", new XAttribute("Include", text5)));
                    }
                }
            }
            xElement3.Add(new XElement(ns + "None", new XAttribute("Include", "Readme.txt")));
            xElement.Add(xElement3);
            xElement.Add(xElement4);
            xElement.Add(new XElement(ns + "Import", new XAttribute("Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets")));
            xElement.Add(new XElement(ns + "ImportGroup", new object[]
			{
				new XAttribute("Label", "ExtensionTargets"),
				""
			}));
            xElement.Save(DocName);
        }

        public void VC_Filters_Create(string[] Targets)
        {
            string DocName = VSProjPath + ProjName + ".filters";
            if (DocName == "")
            {
                return;
            }
            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            XElement xElement = new XElement(ns + "Project", new object[]
			{
				new XAttribute("DefaultTargets", "Build"),
				new XAttribute("ToolsVersion", "4.0")
			});
            XElement xElement2 = new XElement(ns + "ItemGroup", "");
            string text = "源文件";
            xElement2.Add(new object[]
			{
				new XElement(ns + "Filter", new object[]
				{
					new XAttribute("Include", text),
					new XElement(ns + "UniqueIdentifier", Guid.NewGuid().ToString("B")),
					new XElement(ns + "Extensions", "cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx")
				}),
				new XElement(ns + "Filter", new object[]
				{
					new XAttribute("Include", "头文件"),
					new XElement(ns + "UniqueIdentifier", Guid.NewGuid().ToString("B")),
					new XElement(ns + "Extensions", "h;hpp;hxx;hm;inl;inc;xsd")
				}),
				new XElement(ns + "Filter", new object[]
				{
					new XAttribute("Include", "项目说明"),
					new XElement(ns + "UniqueIdentifier", Guid.NewGuid().ToString("B")),
					new XElement(ns + "Extensions", "txt")
				})
			});
            string[] targets = MDK_TargetRead();
            string[] array = MDK_GroupRead(targets[0]);
            string[] array2 = array;
            for (int i = 0; i < array2.Length; i++)
            {
                string str = array2[i];
                xElement2.Add(new XElement(ns + "Filter", new object[]
				{
					new XAttribute("Include", text + "\\" + str),
					new XElement(ns + "UniqueIdentifier", Guid.NewGuid().ToString("B"))
				}));
            }
            xElement.Add(xElement2);
            xElement2 = new XElement(ns + "ItemGroup", "");
            XElement xElement3 = new XElement(ns + "ItemGroup", "");
            string[] array3 = array;
            for (int j = 0; j < array3.Length; j++)
            {
                string text2 = array3[j];
                string[] array4 = MDK_SrcRead(Targets[0], text2);
                string[] array5 = array4;
                for (int k = 0; k < array5.Length; k++)
                {
                    string targetPat = array5[k];
                    string text3 = GetFullPath(KeilProjPath, targetPat);
                    text3 = GetRelativePath(VSProjPath, text3);
                    if (text3.EndsWith(".c"))
                    {
                        xElement3.Add(new XElement(ns + "ClCompile", new object[]
						{
							new XAttribute("Include", text3),
							new XElement(ns + "Filter", text + "\\" + text2)
						}));
                    }
                    else
                    {
                        xElement2.Add(new XElement(ns + "None", new object[]
						{
							new XAttribute("Include", text3),
							new XElement(ns + "Filter", text + "\\" + text2)
						}));
                    }
                }
            }
            xElement2.Add(new XElement(ns + "None", new object[]
			{
				new XAttribute("Include", "Readme.txt"),
				new XElement(ns + "Filter", "项目说明\\")
			}));
            xElement.Add(xElement3);
            xElement.Add(xElement2);
            xElement.Save(DocName);
        }


        public void VC_Create_UserFile(string[] Targets)
        {
            string DocName = VSProjPath + ProjName + ".user";
            if (DocName == "")
            {
                return;
            }
            XNamespace ns = "http://schemas.microsoft.com/developer/msbuild/2003";
            XElement xElement = new XElement(ns + "Project", new XAttribute("ToolsVersion", "4.0"));
            for (int i = 0; i < Targets.Length; i++)
            {
                string newValue = Targets[i];
                xElement.Add(new XElement(ns + "PropertyGroup", new object[]
				{
					new XAttribute("Condition", "'$(Configuration)|$(Platform)'=='Target|Win32'".Replace("Target", newValue)),
					new XElement(ns + "LocalDebuggerCommand", UV4_Path),
					new XElement(ns + "LocalDebuggerCommandArguments", LocalDebuggerCommandArguments.Replace("Target", newValue)),
					new XElement(ns + "LocalDebuggerWorkingDirectory", LocalDebuggerWorkingDirectory),
					new XElement(ns + "DebuggerFlavor", "WindowsLocalDebugger")
				}));
            }
            xElement.Save(DocName);
        }

        public void VC_Creat_readme()
        {
            string DocName = VSProjPath + "Readme.txt";
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.Append("========================================================================\r\n");
            stringBuilder.Append("    生成文件项目：Template 项目概述\r\n"); 
            stringBuilder.Append("    生成项目时间：" + DateTime.Now.ToString() + "\r\n");
            stringBuilder.Append("    生成项目用户：" + Dns.GetHostName() + "\r\n");
            stringBuilder.Append("========================================================================\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("本文件概要介绍组成 Template 项目的每个文件的内容。\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("<Template.sln>\r\n");
            stringBuilder.Append("    这是Template项目的解决方案文件\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("<Template.vcxproj>\r\n");
            stringBuilder.Append("    这是Template项目的主项目文件\r\n");
            stringBuilder.Append("    其中包含了这个项目中的各个Target，\r\n");
            stringBuilder.Append("    以及Include Path、所有源文件的路径、编译命令。\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("<Template.vcxproj.filters>\r\n");
            stringBuilder.Append("    这是Template项目的项目筛选器文件。\r\n");
            stringBuilder.Append("    它包含了这个项目中的所有源文件分组及源文件的路径。\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("<Template.vcxproj.user>\r\n");
            stringBuilder.Append("    这是Template项目的 用户文件，\r\n");
            stringBuilder.Append("    它包含了这个项目中的各个Target的 Debug命令。\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder.Append("以上文件由MDK Project  To Visual Studio Project 工具读取 Keil uVision4\r\n");
            stringBuilder.Append("的项目文件：Template.uvproj 中的设定，按照Visual Studio 2010\r\n");
            stringBuilder.Append("中VC++ “生成文件项目” 的模板文件来生成的，如有疑问，请看MSDN~\r\n");
            stringBuilder.Append("\r\n");
            stringBuilder = stringBuilder.Replace("Template", ProjName);
            FileStream fileStream = File.OpenWrite(DocName);
            byte[] bytes = new UTF8Encoding(true).GetBytes(stringBuilder.ToString());
            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Close();
        }

        public string Convert()
        {
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
            folderBrowserDialog.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog.Description = "Please select the Visual Studio Project Path";
            folderBrowserDialog.SelectedPath = KeilProjPath;

            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                VSProjPath = Path.Combine(new string[]
				{
					folderBrowserDialog.SelectedPath,
					"Visual Studio Project"
				}) + "\\";
                if (!Directory.Exists(VSProjPath))
                {
                    Directory.CreateDirectory(VSProjPath);
                }
            }
            else
            {
                return "";
            }

            string[] targets = MDK_TargetRead();
            string relativePath = GetRelativePath(VSProjPath, KeilProjFullName);
            NMakeBuildCommandLine = string.Concat(new string[]
			{
				"\"",
				UV4_Path,
				"\" -b ",
				relativePath,
				" -t \"Target\" -j0 -o Build.log"
			});
            LocalDebuggerCommandArguments = "-d " + ProjName + ".uvproj -t \"Target\"";
            VC_Creat_Sln(targets);
            VC_Filters_Create(targets);
            VC_vcxproj_Create(targets);
            LocalDebuggerWorkingDirectory = GetRelativePath(VSProjPath, KeilProjPath);
            VC_Create_UserFile(targets);
            VC_Creat_readme();


            if(CreateSln)
            {

            }
            return VSProjPath;
        }

        public void OpenSrcFile(string filename)
        {
            string text = GetFullPath(KeilProjPath, filename);
            new Process
            {
                StartInfo =
                {
                    FileName = "notepad++.exe",
                    Arguments = text
                }
            }.Start();
        }

        public string GetRelativePath(string basePath, string targetPath)
        {
            Uri uri = new Uri(basePath);
            Uri uri2 = new Uri(targetPath);
            return uri.MakeRelativeUri(uri2).ToString().Replace("/", "\\");
        }

        private string GetFullPath(string basePath, string targetPat)
        {
            Uri baseUri = new Uri(basePath);
            Uri uri = new Uri(baseUri, targetPat);
            return uri.ToString().Replace("/", "\\").Replace("file:\\\\\\", "");
        }
    }
}
